import sqlite3
import os
import os.path as osp

def mkdir(dir_name):
    if not osp.exists(dir_name):
        os.makedirs(dir_name, exist_ok=True)
    return

def connectDB(database):
    database_path = './database'
    print('当前'+ database)
    mkdir(database_path)
    database_connect = sqlite3.connect(osp.join(database_path, database))
    # 创建游标
    database_cur = database_connect.cursor() 
    return database_connect, database_cur

def queryKeyvalues(database,table):
    _, database_cur = connectDB(database=database)
    try:
        sql = "select * from %s" %table
        values = database_cur.execute(sql)
        database_cur.description
        database_cur.close
        # results = database_cur.fetchall()  
        # for row in results:  
        #     print(row)
        #     this_str = str(row['endpoint'])
        #     print(this_str) 
        return values
    except:
        database_cur.close
        try:
            # create_tb_cmd='''
            # CREATE TABLE IF NOT EXISTS pod_trace_log
            # (id INTEGER PRIMARY KEY AUTOINCREMENT,
            # ExecID varchar(64),
            # podName varchar(64) NOT NULL,
            # repoName varchar(64) NOT NULL,
            # podSource varchar(64) NOT NULL,
            # podBinarySource varchar(64),
            # podAuthor varchar(255),
            # podEmail varchar(256),
            # podDeployment varchar(256)
            # );
            # '''
            # print("表不存在重新创建===")
            # #主要就是上面的语句 : CREATE TABLE IF NOT EXISTS USER
            # database_cur.execute(create_tb_cmd)
            # values = database_cur.execute(sql)
            return None
        except:
            print("Create table failed")
            return None

def insert_database_table(database_cur, database_connect, table_name, values):
    print('当前表名' + values[0] + values[1])
    try:
        database_cur.execute("INSERT INTO %s VALUES(?,?,?,?,?,?,?,?,?,?);" %\
        table_name, (None,1,values[0],values[1],values[2],values[3],None,values[4],None,values[6]))     
        database_connect.commit()
    except:
        try:
            create_tb_cmd='''
            CREATE TABLE IF NOT EXISTS pod_trace_log
            (id INTEGER PRIMARY KEY AUTOINCREMENT,
            ExecID varchar(64),
            podName varchar(64) NOT NULL,
            repoName varchar(64) NOT NULL,
            podSource varchar(64) NOT NULL,
            podBinarySource varchar(64),
            podAuthor varchar(255),
            podEmail varchar(256),
            podDeployment varchar(256),
            podspecName varchar(64) NOT NULL
            );
            '''
            print("表不存在重新创建",os.error)
            #主要就是上面的语句 : CREATE TABLE IF NOT EXISTS USER
            database_cur.execute(create_tb_cmd)
            insert_database_table(database_cur=database_cur,database_connect=database_connect,table_name='pod_trace_log',values=values)
        except:
            print("Create table failed")
 

